package com.greenhou.config;

import com.greenhou.io.Resources;
import com.greenhou.pojo.Configuration;
import com.greenhou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XMLMapperBuilder {
    private Configuration configuration;
    public XMLMapperBuilder(Configuration configuration) {
        this.configuration=configuration;
    }

    public void parse(InputStream in) throws DocumentException {
        SAXReader saxReader=new SAXReader();
        Document document = saxReader.read(in);
        Element mapper = document.getRootElement();

        String nameSpace=mapper.attributeValue("namespace");
        if(nameSpace==null){
            nameSpace="";
        }

        List<Element> selectNodes=mapper.selectNodes("*");
        if(selectNodes!=null && selectNodes.size() > 0){
            Map<String, MappedStatement> mappedStatementMap=this.configuration.getMappedStatementMap();
            if(mappedStatementMap==null){
                new HashMap<String, MappedStatement>();
            }
            for(Element element:selectNodes){
                MappedStatement mappedStatement=new MappedStatement();
                mappedStatement.setId(element.attributeValue("id"));
                mappedStatement.setParameterType(element.attributeValue("parameterType"));
                mappedStatement.setResultType(element.attributeValue("resultType"));
                mappedStatement.setSql(element.getText());
                mappedStatementMap.put(nameSpace+"."+element.attributeValue("id"),mappedStatement);
//                System.out.println("mappedStatementMap: "+mappedStatement);
                this.configuration.setMappedStatementMap(mappedStatementMap);
            }
        }
    }
}
